// pages/authorize/login/login.js
import Toast from '@vant/weapp/toast/toast';
import {
  codeLogin,
  passwordLogin,
  userInfo
} from "../../../api/authorize/login"
import {
  sendCode,
} from "../../../api/authorize/register"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 1,
    phone: '',
    code: '',
    password: '',
    checked: false,
    showCodeBtn: true
  },
  handleCilck(params) {
    console.log(params)
    this.setData({
      index: params.target.dataset.type
    })
  },
  handleCilckCode() {
    if (!this.data.phone) {
      Toast('请输入手机号');
      return
    }
    
    sendCode({
      type: 'CLIENT_LOGIN',
      phone: this.data.phone
    }).then(res => {
      Toast('验证码已发送');
      this.setData({
        showCodeBtn: false
      })
      this.start()
    })
  },
  start() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },
  finished() {
    this.setData({
      showCodeBtn: true
    })
  },
  handleCilckSubmit() {
    if (!this.data.checked) {
      Toast('请阅读用户与隐私协议并勾选');
      return
    }

    if (this.data.index == 1) {
      codeLogin({
        phone: this.data.phone,
        phoneCode: this.data.code
      }).then(res => {
        wx.setStorageSync('token', res.data.data.token)
        userInfo().then(res => {
          app.globalData.userInfo = res.data.data
          wx.switchTab({
            url: '/pages/index/index',
          })
        })
      })
    } else {
      passwordLogin({
        phone: this.data.phone,
        password: this.data.password
      }).then(res => {
        wx.setStorageSync('token', res.data.data.token)
        userInfo().then(res => {
          app.globalData.userInfo = res.data.data
          wx.switchTab({
            url: '/pages/index/index',
          })
        })

      })
    }

  },
  handleCilckReg() {
    wx.navigateTo({
      url: '/pages/authorize/register/index',
    })
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  goUserConfig(){
    wx.navigateTo({
      url: '/pages/authorize/userConfig/index',
    })
  },
  goConfig(){
    wx.navigateTo({
      url: '/pages/authorize/configs/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})